import 'dart:convert';
import 'package:hrf_app/common/utils/storage.dart';
import 'package:get/get.dart';

import '../api/user/user.dart';
import '../index.dart';
import '../models/user/user_info.dart';

/// 用户服务
class UserService extends GetxService {
  static UserService get to => Get.find();

  String token = '';
  bool loginFlag = false;
  final _profile = UserInfo().obs;

  /// 用户 profile
  UserInfo get profile => _profile.value;

  /// 是否有令牌 token
  bool get hasToken => token.isNotEmpty;

  /// 是否登录
  bool get hasLogin => loginFlag;

  @override
  void onInit() {
    super.onInit();
    token = Storage().getString(Constants.storageToken);
    // 是否登录
    loginFlag = Storage().getBool(Constants.loginFlag);
    // 读 profile
    var profileOffline = Storage().getString(Constants.userInfo);
    if (profileOffline.isNotEmpty) {
      _profile(UserInfo.fromJson(jsonDecode(profileOffline)));
    }
  }

  /// 设置令牌
  Future<void> setToken(String token) async {
    await Storage().setString(Constants.storageToken, token);
    this.token = token;
  }

  /// 设置登录状态
  Future<void> setLoginFlag(bool flag) async {
    await Storage().setBool(Constants.loginFlag, flag);
    loginFlag = flag;
  }

  /// 获取用户 profile
  Future<void> getUserInfo() async {
    if (token.isEmpty) return;
    Map<String, dynamic> result = await UserApi.userInfo();
    UserInfo userInfo = UserInfo.fromJson(result["data"]);
    _profile(userInfo);
    setLoginFlag(true);
    Storage().setString(Constants.userInfo, jsonEncode(userInfo));
  }

  /// 设置用户 profile
  Future<void> setProfile(UserInfo profile) async {
    if (token.isEmpty) return;
    _profile(profile);
    Storage().setString(Constants.userInfo, jsonEncode(profile));
  }

  /// 注销
  Future<void> logout() async {
    await Storage().remove(Constants.loginFlag);
    _profile(UserInfo());
    loginFlag = false;
    token = '';
    await Get.offAllNamed(RouteNames.systemLogin);
  }

  /// 检查是否登录
  Future<bool> checkIsLogin() async {
    if (loginFlag == false) {
      await Get.offAllNamed(RouteNames.systemLogin);
      return false;
    }
    return true;
  }
}
